package com.dnw.fragment;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chaychan.library.BottomBarItem;
import com.chaychan.uikit.TipView;
import com.chaychan.uikit.powerfulrecyclerview.PowerfulRecyclerView;
import com.chaychan.uikit.refreshlayout.BGANormalRefreshViewHolder;
import com.chaychan.uikit.refreshlayout.BGARefreshLayout;
import com.dnw.adapter.FunnysAdapter;
import com.dnw.base.ApiConstant;
import com.dnw.base.BaseFragment;
import com.dnw.event.TabRefreshCompletedEvent;
import com.dnw.event.TabRefreshEvent;
import com.dnw.modle.Funnys;
import com.dnw.modle.FunnysRecord;
import com.dnw.modle.Program;
import com.dnw.modle.Result;
import com.dnw.presenter.FunnysListPresenter;
import com.dnw.shyfunny.R;
import com.dnw.util.AppUtil;
import com.dnw.util.FunnysRecordHelper;
import com.dnw.util.ListUtils;
import com.dnw.util.NetWorkUtils;
import com.dnw.util.SharedPreferencesMgr;
import com.dnw.util.UIUtils;
import com.dnw.view.lFunnysListView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.Bind;

import static com.dnw.base.ApiConstant.SharedPreferencesEnum.PASSED;
import static com.dnw.base.ApiConstant.approvedEnum.NOT_APPROVED;


/**
 * A fragment representing a list of Items.
 * <p/>
 */
public class ShyFragment extends BaseFragment<FunnysListPresenter> implements lFunnysListView, BGARefreshLayout.BGARefreshLayoutDelegate, BaseQuickAdapter.RequestLoadMoreListener{
    @Bind(R.id.tip_view)
    TipView mTipView;

    @Bind(R.id.refresh_layout)
    BGARefreshLayout mRefreshLayout;

    @Bind(R.id.fl_content)
    FrameLayout mFlContent;

    @Bind(R.id.rv_news)
    PowerfulRecyclerView mRvNews;

    private String mChannelCode;
    private String labelName;
    protected FunnysAdapter mFunnysAdapter;
    private boolean isVideoList;
    private List<Funnys> mFunnysList = new ArrayList<>();
    private List<Program> mProgramList = new ArrayList<>();
    private FunnysRecord mFunnysRecord;
    private Gson mGson = new Gson();

    @Override
    protected FunnysListPresenter createPresenter() {
        return new FunnysListPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_news_list;
    }

    @Override
    public View getStateViewRoot() {
        return mFlContent;
    }

    @Override
    public void initData() {
        mChannelCode = "";
        labelName = ApiConstant.ShyTypeEnum.SHY.getDesc();
        isVideoList = false;
    }

    @Override
    public void loadData() {
        mStateView.showLoading();
        //查找该频道的最后一组记录

        //找不到记录，拉取网络数据
        mFunnysRecord = new FunnysRecord();//创建一个没有数据的对象
        mPresenter.refreshFunnysList(mChannelCode, "1", "", labelName);
    }



    @Override
    public void initView(View rootView) {
        mRefreshLayout.setDelegate(this);
        mRvNews.setLayoutManager(new GridLayoutManager(mActivity, 1));
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGANormalRefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(mActivity, false);
        // 设置下拉刷新
        refreshViewHolder.setRefreshViewBackgroundColorRes(R.color.pull_refresh_bg);//背景色
        refreshViewHolder.setPullDownRefreshText(UIUtils.getString(R.string.refresh_pull_down_text));//下拉的提示文字
        refreshViewHolder.setReleaseRefreshText(UIUtils.getString(R.string.refresh_release_text));//松开的提示文字
        refreshViewHolder.setRefreshingText(UIUtils.getString(R.string.refresh_ing_text));//刷新中的提示文字


        // 设置下拉刷新和上拉加载更多的风格
        mRefreshLayout.setRefreshViewHolder(refreshViewHolder);
        mRefreshLayout.shouldHandleRecyclerViewLoadingMore(mRvNews);
    }

    @Override
    public void initListener() {

        mFunnysAdapter = new FunnysAdapter(mActivity, mChannelCode, isVideoList, mFunnysList, mProgramList);
        mRvNews.setAdapter(mFunnysAdapter);

        mFunnysAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Funnys funnys = mFunnysList.get(position);
//
//                String itemId = funnys.id;
//                StringBuffer urlSb = new StringBuffer("http://m.toutiao.com/i");
//                urlSb.append(itemId).append("/info/");
//                String url = urlSb.toString();//http://m.toutiao.com/i6412427713050575361/info/
//                MoveToPosition(mRvNews, 10);
            }
        });

        mFunnysAdapter.setEnableLoadMore(true);
        mFunnysAdapter.setOnLoadMoreListener(this, mRvNews);

    }

    // FIXME: 2017/12/11
    @Override
    public void onLoadMoreRequested() {
        if (!NetWorkUtils.isNetworkAvailable(mActivity)) {
            //网络不可用弹出提示
            mTipView.show();
            if (mRefreshLayout.getCurrentRefreshStatus() == BGARefreshLayout.RefreshStatus.REFRESHING) {
                mRefreshLayout.endRefreshing();
            }
            return;
        }

        FunnysRecord preFunnysRecord = FunnysRecordHelper.getLastFunnysRecord(mChannelCode);
        if (preFunnysRecord == null) {
            // mRefreshLayout.endLoadingMore();//结束加载更多
            mFunnysAdapter.loadMoreEnd();
            return;
        }

        mPresenter.getFunnysList(mChannelCode, preFunnysRecord.getPage()+1+"", "", labelName);
    }
    @Override
    public void onGetFunnysListSuccess(List<Funnys> funnysList, String tipInfo, String pageOn) {
        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新
        if (isHomeTabRefresh) {
            postRefreshCompletedEvent();//发送加载完成的事件
        }
        //如果是第一次获取数据
        if (ListUtils.isEmpty(funnysList)) {
            if (ListUtils.isEmpty(funnysList)) {
                if (ListUtils.isEmpty(funnysList)) {
                    //已经获取不到新闻了，处理出现获取不到新闻的情况
                    UIUtils.showToast(UIUtils.getString(R.string.no_more_now));
                    mFunnysList.addAll(0, funnysList);
                    mFunnysAdapter.notifyDataSetChanged();
                    return;
                }
            }
        }else{
            mStateView.showContent();//显示内容
        }
        dealRepeat(funnysList);//处理新闻重复问题
        if(SharedPreferencesMgr.getBoolean(PASSED.name() + AppUtil.getVersionCode(mActivity), NOT_APPROVED.isStatus())){
            insertProgram();
        }
        mFunnysList.addAll(funnysList);
        mFunnysAdapter.notifyDataSetChanged();
        mFunnysAdapter.loadMoreComplete();
        mTipView.show(tipInfo);
        //保存到数据库

        FunnysRecordHelper.save(mChannelCode, mGson.toJson(funnysList), pageOn);
    }

    @Override
    public void onProgramList(Result<List<Program>> result) {
        mProgramList = result.data;
        mFunnysAdapter.setmPrograms(mProgramList);
//        if(mFunnysList.size() > 9 && mProgramList.size() > 0){
//            Funnys funnys = new Funnys();
//            mFunnysList.add(funnys.getProgramFunny());
//        }
        mFunnysAdapter.notifyDataSetChanged();
        mFunnysAdapter.loadMoreComplete();
        mTipView.show("~~");
        postRefreshCompletedEvent();//发送加载完成的事件
    }

    /**
     * 处理置顶新闻和广告重复
     */
    private void insertProgram() {
        if(mProgramList.size() <= 0){
            mPresenter.progranList();
        }else {
            Funnys funnys = new Funnys();
            mFunnysList.add(funnys.getProgramFunny());
        }
        mFunnysAdapter.notifyDataSetChanged();
        mFunnysAdapter.loadMoreComplete();
        mTipView.show("~~");
        postRefreshCompletedEvent();//发送加载完成的事件
    }
    /**
     * 处理置顶新闻和广告重复
     */
    private void dealRepeat(List<Funnys> funnysList) {
        if (!ListUtils.isEmpty(funnysList)) {
            for(Funnys funnys : mFunnysList){
                for (Funnys funnysNew : funnysList){
                    if(funnys.id.equalsIgnoreCase(funnysNew.id)){
                        funnysList.remove(funnysNew);
                    }
                }
            }
        }
    }


    @Override
    public void onError() {
        mTipView.show();//弹出提示

        if (ListUtils.isEmpty(mFunnysList)) {
            //如果一开始进入没有数据
            mStateView.showRetry();//显示重试的布局
        }

        //收起刷新
        if (mRefreshLayout.getCurrentRefreshStatus() == BGARefreshLayout.RefreshStatus.REFRESHING) {
            mRefreshLayout.endRefreshing();
        }
        postRefreshCompletedEvent();//发送加载完成的事件
    }

    /**
     * 是否是点击底部标签进行刷新的标识
     */
    private boolean isClickTabRefreshing;

    private void postRefreshCompletedEvent() {
        if (isClickTabRefreshing) {
            //如果是点击底部刷新获取到数据的,发送加载完成的事件
            EventBus.getDefault().post(new TabRefreshCompletedEvent());
            isClickTabRefreshing = false;
        }
    }
    //用于标记是否是首页的底部刷新，如果是加载成功后发送完成的事件
    private boolean isHomeTabRefresh;
    private RotateAnimation mRotateAnimation;
    /**
     * 接收到点击底部首页页签下拉刷新的事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(TabRefreshEvent event) {
        if (event.getChannelCode().equals(mChannelCode) && mRefreshLayout.getCurrentRefreshStatus() != BGARefreshLayout.RefreshStatus.REFRESHING) {
            //如果和当前的频道码一致并且不是刷新中,进行下拉刷新
            if (!NetWorkUtils.isNetworkAvailable(mActivity)) {
                //网络不可用弹出提示
                mTipView.show();
                return;
            }

            isClickTabRefreshing = true;

            if (event.isHomeTab()) {
                //如果页签是首页，则换成就加载的图标并执行动画
                BottomBarItem bottomBarItem = event.getBottomBarItem();
                bottomBarItem.setIconSelectedResourceId(R.mipmap.tab_loading);//更换成加载图标
                bottomBarItem.setStatus(true);

                //播放旋转动画
                if (mRotateAnimation == null) {
                    mRotateAnimation = new RotateAnimation(0, 360,
                            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                            0.5f);
                    mRotateAnimation.setDuration(800);
                    mRotateAnimation.setRepeatCount(-1);
                }
                ImageView bottomImageView = bottomBarItem.getImageView();
                bottomImageView.setAnimation(mRotateAnimation);
                bottomImageView.startAnimation(mRotateAnimation);//播放旋转动画
            }

            isHomeTabRefresh = event.isHomeTab();//是否是首页

            mRvNews.scrollToPosition(0);//滚动到顶部
            mRefreshLayout.beginRefreshing();//开始下拉刷新
        }
    }


    /**
     * RecyclerView 移动到当前位置，
     *
     * @param n  要跳转的位置
     */
    public  void MoveToPosition(int n) {
        final LinearLayoutManager manager = (LinearLayoutManager) mRvNews.getLayoutManager();

        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRvNews.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRvNews.getChildAt(n - firstItem).getTop();
            mRvNews.scrollBy(0, top);
        } else {
            mRvNews.scrollToPosition(n);
        }

    }
    /**
     * RecyclerView 移动到当前位置，
     *
     */
    public  void jumpToPosition() {
        if (!NetWorkUtils.isNetworkAvailable(mActivity)) {
            //网络不可用弹出提示
            mTipView.show();
            if (mRefreshLayout.getCurrentRefreshStatus() == BGARefreshLayout.RefreshStatus.REFRESHING) {
                mRefreshLayout.endRefreshing();
            }
            return;
        }
        Random rd = new Random(); //创建一个Random类对象实例
        int randomNum = rd.nextInt(4000)+1;
        FunnysRecord preFunnysRecord = FunnysRecordHelper.getLastFunnysRecord(mChannelCode);
        mPresenter.refreshFunnysList(mChannelCode, randomNum+"", "", labelName);
//        if (preFunnysRecord == null) {
//            mPresenter.refreshFunnysList(mChannelCode, randomNum+"", "");
//        } else {
//            int randomLocal = PreUtils.getInt(mChannelCode+"_randonLocal",0);
//            if(preFunnysRecord.getPage() > randomLocal){
//                randomNum = preFunnysRecord.getPage()+randomNum;
//            }else {
//                randomNum = randomLocal + randomNum;
//            }
//            mPresenter.refreshFunnysList(mChannelCode, randomNum +"", "");
//        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {

        if (!NetWorkUtils.isNetworkAvailable(mActivity)) {
            //网络不可用弹出提示
            mTipView.show();
            if (mRefreshLayout.getCurrentRefreshStatus() == BGARefreshLayout.RefreshStatus.REFRESHING) {
                mRefreshLayout.endRefreshing();
            }
            return;
        }
        mPresenter.refreshFunnysList(mChannelCode, "1", "", labelName);
    }

    @Override
    public void onRefreshFunnysListSuccess(List<Funnys> funnysList, String tipInfo, String pageOn) {
        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新

        //如果是第一次获取数据
        if (ListUtils.isEmpty(funnysList)) {
            if (ListUtils.isEmpty(funnysList)) {
                //已经获取不到新闻了，处理出现获取不到新闻的情况
                UIUtils.showToast(UIUtils.getString(R.string.no_more_now));
                mFunnysList.addAll(0, funnysList);
                mFunnysAdapter.notifyDataSetChanged();
                return;
            }
        }else{
            mStateView.showContent();//显示内容
        }

        mFunnysList.clear();
        mFunnysList.addAll(0, funnysList);
        mFunnysAdapter.notifyDataSetChanged();
        MoveToPosition(0);
        mTipView.show(tipInfo);
        FunnysRecordHelper.deleteFunnysRecord(mChannelCode);
        //保存到数据库
        FunnysRecordHelper.save(mChannelCode, mGson.toJson(funnysList), pageOn);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }

}
